% *** Calculate Signal to noise ratio ***
%   Created date : 25 Oct 2013
%   Modified date : 25 Oct 2013
%   Author : Sungjin Kim
%   Description : max_value_of_peak / rms_of_noise
%                   c_args{1} = 1 : real part
%                   c_args{1} = 2 : imaginary part
%                   c_args{1} = 3 : magnitude part
%   Arguments : 1D data array, noise range array, # of peak, ...
%
% ************************************************************************

function [snr, indxPeak]= mrsSNR(arr_spectrum, arr_noise_range_P, peakSelector, c_args)

    if c_args{1} == 1
        arr_spectrum = real(arr_spectrum);
    elseif c_args{1} == 2
        arr_spectrum = imag(arr_spectrum);
    elseif c_args{1} == 3
        arr_spectrum = abs(arr_spectrum);
    else
        fprintf('[ERROR] c_args\n');
    end
    
    % calculate a rms of noise
    est_noise = arr_spectrum(arr_noise_range_P(1,1) : arr_noise_range_P(1,2));
    rms_noise = rms(est_noise);
    
    % select a peak
    data_size = size(arr_spectrum);
    arr_mark_peak = zeros(data_size(1), 1);
    diff_spectrum = diff(arr_spectrum);
    diff_size=size(diff_spectrum);
    
    for indx = 1:1:diff_size(1)-1
        if (diff_spectrum(indx) > 0) && (diff_spectrum(indx+1) <= 0)
            arr_mark_peak(indx+1) = arr_spectrum(indx+1);
        end
    end
    
%     % Display
%     figure(11);
%     plot(arr_mark_peak);
%     hold on;
%     plot(arr_spectrum,'red');
%     grid on;
    
    % search a peak
    for indx = 1:1:peakSelector
        [valuePeak, indxPeak] = max(arr_mark_peak);
        arr_mark_peak(indxPeak) = 0;
    end
        
    % calculate snr
    snr = valuePeak/rms_noise;

end % end of data
